<template>
    <div>
        <div class="tDsReportTable" ref="tDsReportTable">
            <vxe-table show-overflow :height="curHeight" row-id="id" :loading="loading1" :data="tableData1" ref="xTable">
                <vxe-table-column field="AC_NAME" title="账户名称" fixed> </vxe-table-column>
                <vxe-table-column field="AC_ID" title="账户ID" width="120"> </vxe-table-column>
                <vxe-table-column field="USER_NAME" title="用户名称"> </vxe-table-column>
                <vxe-table-column field="AC_SUM" title="账户余额" width="90"> </vxe-table-column>
                <vxe-table-column field="FREE_SUM" title="补助余额" width="90"> </vxe-table-column>
                <vxe-table-column field="OVER_SUM" title="透支状态" width="100"> </vxe-table-column>
                <vxe-table-column field="IS_PUBLIC" title="公共账户" width="80"></vxe-table-column>
                <vxe-table-column field="AC_STATE" title="账户状态" width="80"></vxe-table-column>
                <vxe-table-column field="EQ_COUNT" title="设备数量" width="80"></vxe-table-column>
                <vxe-table-column field="COM_CYCLE_TIME" title="结算时间" width="140"></vxe-table-column>
                <vxe-table-column field="id" title="操作" width="60">
                    <template slot-scope="scope">
                        <a style="color: #2680fa" @click="print(scope.row)">{{ scope.row.id ? '打印' : '打印' }}</a>
                    </template>
                </vxe-table-column>
            </vxe-table>

            <vxe-pager
                :loading="loading1"
                :current-page="tablePage1.currentPage"
                :page-size="tablePage1.pageSize"
                :total="tablePage1.totalResult"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Total', 'Sizes']"
                @page-change="handlePageChange1"
            >
            </vxe-pager>
        </div>

        <tDsReportPrint v-if="showPrint" :orderId="curItem.id" :time="curItem.COM_CYCLE_TIME" @close="showPrint = false"></tDsReportPrint>
    </div>
</template>

<script>
import {AjaxCommon} from '@/libs/apiCommon'
import qs from 'qs'
import {PopupCommon} from '@/libs/popupCommon'
import {formatDecimal} from '@/libs/tools'
import html2pdf from 'html2pdf.js'
import {Document, Packer, Paragraph, Table, TableRow, TableCell, TextRun} from 'docx'
import {saveAs} from 'file-saver'
import tDsReportPrint from '@/view/managementCenter/dataReportCenter/components/tDsReportPrint'
import moment from 'moment'
export default {
    name: 'tDsReportTable',
    components: {tDsReportPrint},
    data() {
        return {
            showPrint: false,
            curHeight: document.body.clientHeight - 290,
            params: {},
            loading1: false,
            tableData1: [],
            tablePage1: {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
            },
            curItem: {}
        }
    },
    computed: {},
    created() {},
    methods: {
        getNum(num) {
            return formatDecimal(num)
        },
        print(item) {
            this.curItem = item
            this.showPrint = true
        },
        exportExcel(type) {
            if (type == 'excel') {
                // 调用内置导出方法
                this.$refs.xTable.exportData({
                    filename: '欠费明细统计报表', // 文件名
                    sheetName: '欠费明细统计报表', // 工作表名称
                    type: 'xlsx', // 导出类型（xlsx/csv）
                    // 可选：自定义导出列
                    columns: [
                        {field: 'AC_NAME', title: '账户名称'},
                        {field: 'AC_ID', title: '账户ID'},
                        {field: 'USER_NAME', title: '用户名称'},
                        {field: 'AC_SUM', title: '账户余额'},
                        {field: 'FREE_SUM', title: '补助余额'},
                        {field: 'OVER_SUM', title: '透支状态'},
                        {field: 'IS_PUBLIC', title: '公共账户'},
                        {field: 'AC_STATE', title: '账户状态'},
                        {field: 'EQ_COUNT', title: '设备数量'},
                        {field: 'COM_CYCLE_TIME', title: '结算时间'}
                    ]
                })
            } else if (type == 'pdf') {
                const content = this.$refs.tDsReportTable
                const opt = {
                    margin: 10,
                    filename: '欠费明细统计.pdf',
                    image: {type: 'jpeg', quality: 0.98},
                    html2canvas: {scale: 2}, // 提升清晰度
                    jsPDF: {unit: 'mm', format: 'a4', orientation: 'portrait'}
                }
                // 执行导出
                html2pdf().set(opt).from(content).save()
            } else {
                // 1. 创建Word文档
                const doc = new Document({
                    creator: 'admin', // 显式指定 creator（可选，避免默认值 undefined）
                    title: '欠费明细统计',
                    sections: [
                        // 必须是数组！
                        {
                            // 节的配置（包含子元素）
                            children: [
                                // 标题
                                new Paragraph({
                                    children: [new TextRun({text: '欠费明细统计', bold: true, size: 24})],
                                    alignment: 'center'
                                }),
                                // // 总计信息
                                // new Paragraph(`总计金额：¥${this.totalAmount || 0}`),
                                // new Paragraph(`记录数：${this.tableData?.length || 0} 条`),
                                new Paragraph(''), // 空行
                                // 表格（明细数据）
                                new Table({
                                    rows: [
                                        // 表头行
                                        new TableRow({
                                            children: [
                                                new TableCell({children: [new Paragraph('账户名称')]}),
                                                new TableCell({children: [new Paragraph('账户ID')]}),
                                                new TableCell({children: [new Paragraph('用户名称')]}),
                                                new TableCell({children: [new Paragraph('账户余额')]}),
                                                new TableCell({children: [new Paragraph('补助余额')]}),
                                                new TableCell({children: [new Paragraph('透支状态')]}),
                                                new TableCell({children: [new Paragraph('公共账户')]}),
                                                new TableCell({children: [new Paragraph('账户状态')]}),
                                                new TableCell({children: [new Paragraph('设备数量')]}),
                                                new TableCell({children: [new Paragraph('结算时间')]})
                                            ]
                                        }),
                                        // 数据行
                                        ...this.tableData1.map(
                                            (item) =>
                                                new TableRow({
                                                    children: [
                                                        new TableCell({children: [new Paragraph(item.AC_NAME)]}),
                                                        new TableCell({children: [new Paragraph(item.AC_ID)]}),
                                                        new TableCell({children: [new Paragraph(item.USER_NAME)]}),
                                                        new TableCell({children: [new Paragraph(item.AC_SUM)]}),
                                                        new TableCell({children: [new Paragraph(item.FREE_SUM)]}),
                                                        new TableCell({children: [new Paragraph(item.OVER_SUM)]}),
                                                        new TableCell({children: [new Paragraph(item.IS_PUBLIC)]}),
                                                        new TableCell({children: [new Paragraph(item.AC_STATE)]}),
                                                        new TableCell({children: [new Paragraph(item.EQ_COUNT)]}),
                                                        new TableCell({children: [new Paragraph(item.COM_CYCLE_TIME)]})
                                                    ]
                                                })
                                        )
                                    ]
                                }),
                                // 分页信息
                                new Paragraph(''),
                                new Paragraph(`当前页：${this.tablePage1?.currentPage || 1} / ${this.tablePage1?.pageSize || 1}`, {
                                    alignment: 'right'
                                })
                            ]
                        }
                    ]
                })

                // 5. 生成并导出Word
                Packer.toBlob(doc)
                    .then((blob) => {
                        saveAs(blob, '欠费明细统计.docx')
                    })
                    .catch((err) => {
                        console.error('导出失败：', err)
                    })
            }
        },
        getAllData() {
            return this.tableData1 ?? []
        },
        async getData(params) {
            this.params = params
            this.loading1 = true
            const res = await AjaxCommon(`/api/Payment/GetAcBalance?${qs.stringify(params)}`, 'get', null)
            if (res?.data?.Code == 200) {
                const data = res?.data.Message
                this.tableData1 = data.rows?.map((t, i) => {
                    t.id = t.AC_GUID
                    t.COM_CYCLE_TIME = moment(t.COM_CYCLE_TIME).format('YYYY-MM-DD HH:mm')
                    t.OVER_SUM = t.OVER_SUM == '-1' ? '无限制透支' : parseInt(t.OVER_SUM) == 0 ? '不允许透支' : this.getNum(t.OVER_SUM)
                    t.AC_SUM = this.getNum(t.AC_SUM)
                    t.FREE_SUM = this.getNum(t.FREE_SUM)
                    return t
                })
            } else {
                this.tableData1 = []
            }
            this.loading1 = false
            this.tablePage1.totalResult = parseInt(res?.data.Message?.total ?? 0)
        },

        handlePageChange1({currentPage, pageSize}) {
            this.tablePage1.currentPage = currentPage
            this.tablePage1.pageSize = pageSize
            this.getData(this.params)
        }
    }
}
</script>

<style lang="scss" scoped>
</style>